<?php

namespace App\Http\Controllers\Api\Student;

use App\Models\Course;
use App\Models\Knowledge;
use App\Models\Paper;
use App\Models\Question;
use App\Models\Student;
use App\Models\StudentKnowledgeProgress;
use App\Models\StudentPaperRecord;
use App\Models\StudentWrongQuestion;
use App\Models\VirtualClassroom;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class StudentController extends Controller
{
    /**
     * 接口1：首页内容
     * GET /api/student/home
     */
    public function home(Request $request)
    {
        $student = auth('student')->user();
        if (!$student instanceof Student) {
            return $this->error('身份认证失败', 401);
        }

        // 获取个人信息（使用 only() 方法）
        $userInfo = $student->only(['id', 'name', 'username', 'phone', 'avatar', 'created_at']);
        
        // 处理 id_card：返回脱敏后的身份证号（前3后4，中间用*替代）
        // if ($student->id_card) $userInfo['id_card'] = $this->maskIdCard($student->id_card);
        if ($student->id_card) $userInfo['id_card'] = $student->id_card;

        // 2. 绑定的课程列表（含知识和试卷进度）
        $courses = Course::whereHas('students', function ($q) use ($student) {
            $q->where('student_id', $student->id);
        })->with('category:id,name')->get();

        $courseList = [];
        foreach ($courses as $course) {
            $courseId = $course->id;
            // 知识进度计算
            $knowledgeIds = $course->knowledges->pluck('id')->toArray();
            $knowledgeCount = count($knowledgeIds);
            $learnedCount = StudentKnowledgeProgress::where([
                'student_id' => $student->id,
                'course_id' => $courseId
            ])->whereIn('knowledge_id', $knowledgeIds)
              ->where('status', 1)->count();
            $knowledgeProgress = $knowledgeCount > 0 
                ? round(($learnedCount / $knowledgeCount) * 100) . '%' 
                : '0%';

            // 试卷进度计算
            $paperIds = $course->papers->pluck('id')->toArray();
            $paperCount = count($paperIds);
            $finishedCount = StudentPaperRecord::where([
                'student_id' => $student->id,
                'course_id' => $courseId
            ])->whereIn('paper_id', $paperIds)
              ->where('status', 1)->count();
            $paperProgress = $paperCount > 0 
                ? round(($finishedCount / $paperCount) * 100) . '%' 
                : '0%';

            $courseList[] = array_merge($course->toArray(), [
                'knowledge_progress' => $knowledgeProgress,
                'paper_progress' => $paperProgress
            ]);
        }

        // 3. 虚拟教室成绩列表
        $virtualScores = VirtualClassroom::where('student_id', $student->id)
            ->orderBy('end_time', 'desc')
            ->take(5) // 取最近5条
            ->get(['id', 'project_name', 'status', 'score', 'end_time']);

        $data = [
            'user_info' => $userInfo,
            'course_list' => $courseList,
            'virtual_classroom_scores' => $virtualScores
        ];
        
        return $this->success($data);
    }

    /**
     * 接口2：课程列表
     * GET /api/student/courses
     */
    public function courseList(Request $request)
    {
        $studentId = auth('student')->id();
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        $courses = Course::whereHas('students', function ($q) use ($studentId) {
            $q->where('student_id', $studentId);
        })->with('category:id,name')
          ->paginate($pageSize, ['*'], 'page', $page);

        $courseItems = [];
        foreach ($courses->items() as $course) {
            // 计算学习进度
            $totalKnowledge = $course->knowledges()->count();
            
            // 查询已学习的知识点数量
            $learnedKnowledge = StudentKnowledgeProgress::where('student_id', $studentId)
                ->where('course_id', $course->id)
                ->where('status', 1)  // status=1 表示已学习
                ->count();
            
            $progress = $totalKnowledge > 0 ? round(($learnedKnowledge / $totalKnowledge) * 100) : 0;
            
            // 调试日志
            // \Log::info("课程进度计算", [
            //     'course_id' => $course->id,
            //     'course_name' => $course->name,
            //     'student_id' => $studentId,
            //     'total_knowledge' => $totalKnowledge,
            //     'learned_knowledge' => $learnedKnowledge,
            //     'progress' => $progress
            // ]);
            
            $courseItems[] = [
                'id' => $course->id,
                'name' => $course->name,
                'code' => $course->code,
                'category' => $course->category,
                'knowledge_count' => $totalKnowledge,
                'paper_count' => $course->papers()->count(),
                'progress' => $progress  // 添加进度字段
            ];
        }

        return $this->paginated($courseItems, $courses);
    }

    /**
     * 接口3：课程详情
     * GET /api/student/course-detail
     */
    public function courseDetail(Request $request)
    {
        $request->validate(['course_id' => 'required|integer|exists:courses,id']);
        $studentId = auth('student')->id();
        $courseId = $request->input('course_id');

        // 验证课程绑定关系
        $isBound = Course::where('id', $courseId)
            ->whereHas('students', function ($q) use ($studentId) {
                $q->where('student_id', $studentId);
            })->exists();
        if (!$isBound) {
            return $this->error('未绑定该课程', 403);
        }

        // 课程基本信息
        $course = Course::with('category:id,name')->findOrFail($courseId);

        // 知识列表（含学习状态）
        $knowledges = Knowledge::whereHas('courses', function ($q) use ($courseId) {
            $q->where('course_id', $courseId);
        })->with('category:id,name')->get();

        $knowledgeList = [];
        foreach ($knowledges as $knowledge) {
            $progress = StudentKnowledgeProgress::where([
                'student_id' => $studentId,
                'course_id' => $courseId,
                'knowledge_id' => $knowledge->id
            ])->first();
            $knowledgeList[] = array_merge($knowledge->toArray(), [
                'learned_status' => $progress ? $progress->status : 0
            ]);
        }

        // 试卷列表（含完成状态和分数）
        $papers = Paper::whereHas('courses', function ($q) use ($courseId) {
            $q->where('course_id', $courseId);
        })->get();

        $paperList = [];
        foreach ($papers as $paper) {
            $record = StudentPaperRecord::where([
                'student_id' => $studentId,
                'course_id' => $courseId,
                'paper_id' => $paper->id
            ])->first();
            $paperList[] = [
                'id' => $paper->id,
                'name' => $paper->name,
                'question_count' => $paper->questions()->count(),
                'type' => $paper->type,
                'status' => $record ? $record->status : 0,
                'score' => $record ? $record->score : null
            ];
        }

        $data = [
            'course_info' => $course,
            'knowledge_list' => $knowledgeList,
            'paper_list' => $paperList
        ];
        
        return $this->success($data);
    }

    /**
     * 接口4-1：试卷详情（考试接口）
     * GET /api/student/paper-detail
     */
    public function paperDetail(Request $request)
    {
        $request->validate([
            'course_id' => 'required|integer|exists:courses,id',
            'paper_id' => 'required|integer|exists:papers,id'
        ]);
        $studentId = auth('student')->id();
        $courseId = $request->input('course_id');
        $paperId = $request->input('paper_id');

        // 验证：试卷属于课程且学生绑定课程
        $isValid = Paper::where('id', $paperId)
            ->whereHas('courses', function ($q) use ($courseId) {
                $q->where('course_id', $courseId);
            })->whereHas('courses.students', function ($q) use ($studentId) {
                $q->where('student_id', $studentId);
            })->exists();
        if (!$isValid) {
            return $this->error('无权访问该试卷', 403);
        }

        // 获取试卷及题目（隐藏正确答案）
        $paper = Paper::with(['questions:id,content,type,options,explanation'])->findOrFail($paperId);
        return $this->success($paper);
    }

    /**
     * 接口4-2：提交试卷并评分
     * POST /api/student/submit-paper
     */
    public function submitPaper(Request $request)
    {
        $request->validate([
            'course_id' => 'required|integer|exists:courses,id',
            'paper_id' => 'required|integer|exists:papers,id',
            'answers' => 'required|array', // 格式: {question_id: answer, ...}
            'answers.*' => 'string'
        ]);

        $studentId = auth('student')->id();
        $courseId = $request->input('course_id');
        $paperId = $request->input('paper_id');
        $studentAnswers = $request->input('answers');

        // 获取试卷题目（含正确答案和选项）
        $paper = Paper::with('questions:id,content,type,answer,options,explanation')->findOrFail($paperId);
        $questions = $paper->questions;
        $total = count($questions);
        if ($total === 0) {
            return $this->error('试卷无题目', 422);
        }

        // 判分逻辑
        $scorePerQuestion = 100 / $total;
        $correctCount = 0;
        $wrongQuestions = [];

        foreach ($questions as $question) {
            $studentAnswer = $studentAnswers[$question->id] ?? '';
            
            // 解析选项，将正确答案文本转换为选项字母
            $correctAnswerLetter = $this->getAnswerLetter($question->answer, $question->options);
            
            // 将学生答案文本也转换为选项字母（如果学生提交的是文本）
            $studentAnswerLetter = $this->getAnswerLetter($studentAnswer, $question->options);
            
            // 标准化答案（去空格、转大写）
            $standardStudentAnswer = strtoupper(trim($studentAnswerLetter));
            $standardCorrectAnswer = strtoupper(trim($correctAnswerLetter));

            // 多选题需要排序后比较
            if ($question->type == 2) {
                // 多选题答案格式: "A,B,C"
                $studentParts = explode(',', $standardStudentAnswer);
                $correctParts = explode(',', $standardCorrectAnswer);
                sort($studentParts);
                sort($correctParts);
                $isCorrect = (implode(',', $studentParts) === implode(',', $correctParts));
            } else {
                $isCorrect = ($standardStudentAnswer === $standardCorrectAnswer);
            }

            if ($isCorrect) {
                $correctCount++;
            } else {
                $wrongQuestions[] = [
                    'student_id' => $studentId,
                    'course_id' => $courseId,
                    'paper_id' => $paperId,
                    'question_id' => $question->id,
                    'student_answer' => $studentAnswerLetter, // 保存转换后的字母格式
                    'correct_answer' => $correctAnswerLetter, // 保存字母格式
                    'explanation' => $question->explanation
                ];
            }
        }

        // 计算总分
        $totalScore = round($correctCount * $scorePerQuestion, 2);

        // 保存试卷记录
        $record = StudentPaperRecord::updateOrCreate(
            ['student_id' => $studentId, 'course_id' => $courseId, 'paper_id' => $paperId],
            [
                'score' => $totalScore,
                'status' => 1,
                'finished_at' => Carbon::now()
            ]
        );

        // 保存错题
        if (!empty($wrongQuestions)) {
            StudentWrongQuestion::insert($wrongQuestions);
        }

        // 格式化错题详情，包含题目内容和选项
        $wrongQuestionsDetail = [];
        foreach ($wrongQuestions as $wq) {
            $question = $questions->firstWhere('id', $wq['question_id']);
            if ($question) {
                $wrongQuestionsDetail[] = [
                    'question_id' => $wq['question_id'],
                    'question_content' => $question->content,
                    'question_type' => $question->type,
                    'options' => $question->options,
                    'student_answer' => $wq['student_answer'],
                    'correct_answer' => $wq['correct_answer'],
                    'explanation' => $wq['explanation']
                ];
            }
        }

        // 格式化所有题目的正确答案（供前端展示答题详情使用）
        $correctAnswers = [];
        foreach ($questions as $question) {
            $correctAnswerLetter = $this->getAnswerLetter($question->answer, $question->options);
            $correctAnswers[$question->id] = $correctAnswerLetter;
        }

        $data = [
            'score' => $totalScore,
            'correct_count' => $correctCount,
            'total_count' => $total,
            'wrong_count' => count($wrongQuestions),
            'wrong_questions' => $wrongQuestionsDetail,
            'correct_answers' => $correctAnswers  // 新增：所有题目的正确答案
        ];
        
        return $this->success($data);
    }

    /**
     * 接口4-3：获取试卷结果（查看已完成的试卷成绩和错题）
     * GET /api/student/paper-result
     */
    public function paperResult(Request $request)
    {
        $request->validate([
            'course_id' => 'required|integer|exists:courses,id',
            'paper_id' => 'required|integer|exists:papers,id'
        ]);

        $studentId = auth('student')->id();
        $courseId = $request->input('course_id');
        $paperId = $request->input('paper_id');

        // 获取试卷记录
        $record = StudentPaperRecord::where([
            'student_id' => $studentId,
            'course_id' => $courseId,
            'paper_id' => $paperId
        ])->first();

        if (!$record) {
            return $this->error('未找到试卷记录', 404);
        }

        // 获取错题列表
        $wrongQuestions = StudentWrongQuestion::where([
            'student_id' => $studentId,
            'course_id' => $courseId,
            'paper_id' => $paperId
        ])->get();

        // 获取试卷总题数（需要包含answer字段来生成正确答案）
        $paper = Paper::with('questions:id,content,type,answer,options,explanation')->findOrFail($paperId);
        $totalCount = $paper->questions->count();

        // 格式化错题详情
        $wrongQuestionsDetail = [];
        foreach ($wrongQuestions as $wq) {
            $question = $paper->questions->firstWhere('id', $wq->question_id);
            if ($question) {
                $wrongQuestionsDetail[] = [
                    'question_id' => $wq->question_id,
                    'question_content' => $question->content,
                    'question_type' => $question->type,
                    'options' => $question->options,
                    'student_answer' => $wq->student_answer,
                    'correct_answer' => $wq->correct_answer,
                    'explanation' => $wq->explanation
                ];
            }
        }

        // 格式化所有题目的正确答案（供前端展示答题详情使用）
        $correctAnswers = [];
        foreach ($paper->questions as $question) {
            $correctAnswerLetter = $this->getAnswerLetter($question->answer, $question->options);
            $correctAnswers[$question->id] = $correctAnswerLetter;
        }

        $data = [
            'score' => $record->score,
            'correct_count' => $totalCount - count($wrongQuestions),
            'total_count' => $totalCount,
            'wrong_count' => count($wrongQuestions),
            'wrong_questions' => $wrongQuestionsDetail,
            'correct_answers' => $correctAnswers  // 新增：所有题目的正确答案
        ];

        return $this->success($data);
    }

    /**
     * 接口5：虚拟教室成绩列表
     * GET /api/student/virtual-classroom-scores
     */
    public function virtualClassroomScores(Request $request)
    {
        $studentId = auth('student')->id();
        $status = $request->input('status');
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        $query = VirtualClassroom::where('student_id', $studentId);
        if (isset($status)) {
            $query->where('status', $status);
        }

        $scores = $query->orderBy('end_time', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);

        return $this->paginated($scores->items(), $scores);
    }

    /**
     * 接口6：修改个人信息
     * PUT /api/student/profile
     */
    public function updateProfile(Request $request)
    {
        // 1. 获取认证的学生模型实例
        $student = auth('student')->user();
        // 验证是否获取到模型（未认证或令牌无效）
        if (!$student instanceof Student) {
            return $this->error('身份认证失败', 401);
        }
        
        // 2. 验证输入数据
        $validated = $request->validate([
            'name' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:20|unique:students,phone,' . $student->id,
            'avatar' => 'nullable|string',
            'email' => 'nullable|email|unique:students,email,' . $student->id,
            'id_card' => 'nullable|string|max:18',
            'old_password' => 'nullable|string', // 旧密码
            'password' => 'nullable|string|min:6|confirmed', // 新密码，需要确认
            'password_confirmation' => 'nullable|string' // 确认新密码
        ], [
            'phone.unique' => '该手机号已被使用',
            'email.unique' => '该邮箱已被使用',
            'password.min' => '密码长度至少6位',
            'password.confirmed' => '两次输入的密码不一致'
        ]);

        // 3. 如果提供了新密码，验证旧密码
        if (!empty($validated['password'])) {
            // 检查是否提供了旧密码
            if (empty($validated['old_password'])) {
                return $this->error('修改密码时必须提供旧密码', 422);
            }
            
            // 验证旧密码是否正确
            if (!Hash::check($validated['old_password'], $student->password)) {
                return $this->error('旧密码不正确', 422);
            }
        }

        $avatarData = $request->input('avatar');
        // 如果提供了base64格式的头像数据，则进行处理
        if ($avatarData && preg_match('/^data:image\/(\w+);base64,/', $avatarData, $matches)) {
            $extension = $matches[1];
            $imageData = substr($avatarData, strpos($avatarData, ',') + 1);
            $imageData = base64_decode($imageData);
            
            if ($imageData !== false) {
                // 生成唯一文件名
                $filename = 'avatar_' . Str::random(32) . '.' . $extension;
                $path = 'avatars/' . date('Y/m');
                
                // 保存文件到存储目录
                Storage::disk('public')->put($path . '/' . $filename, $imageData);
                
                // 获取文件路径
                $avatarData = Storage::url($path . '/' . $filename);
            }
        } 

        // 4. 更新基本信息
        $updateData = [];
        if (isset($validated['name'])) $updateData['name'] = $validated['name'];
        if (isset($validated['phone'])) $updateData['phone'] = $validated['phone'];
        if (isset($validated['avatar'])) $updateData['avatar'] = $avatarData;
        if (isset($validated['email'])) $updateData['email'] = $validated['email'];
        if (isset($validated['id_card'])) $updateData['id_card'] = $validated['id_card'];
        
        // 5. 如果提供了新密码，更新密码
        if (!empty($validated['password'])) {
            $updateData['password'] = bcrypt($validated['password']);
        }
        
        // 6. 执行更新
        $student->update($updateData);

        $data = $student->only(['id', 'name', 'phone', 'avatar', 'email']);
        
        // 7. 根据是否修改密码返回不同消息
        $message = !empty($validated['password']) ? '个人信息更新成功，密码已修改' : '个人信息更新成功';
        
        return $this->success($data, $message);
    }

    /**
     * 辅助接口：标记知识为已学习
     * POST /api/student/mark-knowledge
     */
    public function markKnowledge(Request $request)
    {
        $request->validate([
            'course_id' => 'required|integer|exists:courses,id',
            'knowledge_id' => 'required|integer|exists:knowledges,id'
        ]);

        $studentId = auth('student')->id();
        $courseId = $request->input('course_id');
        $knowledgeId = $request->input('knowledge_id');

        // 验证知识属于课程
        $isValid = Knowledge::where('id', $knowledgeId)
            ->whereHas('courses', function ($q) use ($courseId) {
                $q->where('course_id', $courseId);
            })->exists();
        if (!$isValid) {
            return $this->error('知识不属于该课程', 422);
        }

        // 创建或更新学习进度（标记为已学习）
        StudentKnowledgeProgress::updateOrCreate(
            [
                'student_id' => $studentId,
                'course_id' => $courseId,
                'knowledge_id' => $knowledgeId
            ],
            [
                'status' => 1,
                'learned_at' => now()
            ]
        );

        return $this->success(null, '已标记为已学习');
    }

    /**
     * 将答案文本转换为选项字母
     * @param string $answerText - 答案文本，如"正确"或"正确,错误"
     * @param string $optionsJson - 选项JSON字符串，如'["A.正确","B.错误"]'
     * @return string - 返回选项字母，如"A"或"A,B"
     */
    private function getAnswerLetter($answerText, $optionsJson)
    {
        if (empty($answerText) || empty($optionsJson)) {
            return $answerText;
        }
        
        try {
            $options = json_decode($optionsJson, true);
            if (!is_array($options)) {
                return $answerText;
            }
            
            // 处理多个答案（多选题）
            $answerParts = array_map('trim', explode(',', $answerText));
            $resultLetters = [];
            
            foreach ($answerParts as $answerPart) {
                foreach ($options as $option) {
                    // 选项格式: "A.正确" 或 "正确"
                    if (preg_match('/^([A-Z])\.(.+)$/', $option, $matches)) {
                        $letter = $matches[1];
                        $text = $matches[2];
                        
                        if (trim($text) === $answerPart) {
                            $resultLetters[] = $letter;
                            break;
                        }
                    } else {
                        // 没有字母前缀，直接比较文本（这种情况返回原答案）
                        if (trim($option) === $answerPart) {
                            return $answerText;
                        }
                    }
                }
            }
            
            return !empty($resultLetters) ? implode(',', $resultLetters) : $answerText;
        } catch (\Exception $e) {
            return $answerText;
        }
    }

    /**
     * 脱敏身份证号
     * 显示前3位和后4位，中间用*替代
     * @param string|null $idCard
     * @return string
     */
    private function maskIdCard($idCard)
    {
        if (empty($idCard)) {
            return '';
        }
        
        $len = mb_strlen($idCard);
        if ($len <= 7) {
            // 长度不足7位，保留后4位
            return str_repeat('*', max(0, $len - 4)) . mb_substr($idCard, -min(4, $len));
        }
        
        $left = mb_substr($idCard, 0, 3);
        $right = mb_substr($idCard, -4);
        $middleLen = $len - 7;
        
        return $left . str_repeat('*', $middleLen) . $right;
    }
}
